// 事件循环机制大体分为三个阶段 timer(setTimeout) -> io回调操作 -> check(setImmdiate)
// process.nextTick 和 promise是在进入阶段前需要执行完成的
// readFile是异步读取文件 readFileSync 是同步阻塞读取文件
const { readFile,readFileSync } = require('fs');
const { resolve } = require('path')

setImmediate( () => { 
    console.log(`[阶段3.immediate] immediate 回调0`)
    setImmediate (() => console.log(`增加的回调`))
})
setImmediate( () => console.log(`[阶段3.immediate] immediate 回调1`))
setImmediate( () => console.log(`[阶段3.immediate] immediate 回调2`))
setImmediate( () => console.log(`[阶段3.immediate] immediate 回调3`))

Promise.resolve().then( () => {
    console.log(`[...待切入下一阶段] promise 回调1`)

    setImmediate( () => {
        console.log(`[阶段3.immediate] promise 回调1 增加的immediate 回调4 `)
    } )
})

readFile('../package.json','utf-8',data => {
    //同步 阻塞后面代码执行
    console.log(`这里正在同步阻塞的读一个大文件`)
    const video = readFileSync(resolve(__dirname,`../test.mp4`),`utf-8`)
    console.log(`[阶段2...IO 回调] 读取文件回调1`);

    readFile(`../test.mp4`,`utf-8`,data => {
        console.log(`[阶段2...IO 回调] 读文件回调2`);
        setImmediate( () => {
            console.log(`[阶段3.immediate] 读文件回调2 增加的immediate 回调4`)
        })
    })
})



setTimeout( () => console.log(`[阶段1...定时器] 定时器 回调1`),0)
setTimeout( () => {
    console.log(`[阶段1 定时器] 定时器 回调2`)
    process.nextTick( () => {
        console.log(`[...待切入下一阶段] nextTick 回调5`)
    })
},0)
setTimeout( () => console.log(`[阶段1...定时器] 定时器 回调3`),0)
setTimeout( () => console.log(`[阶段1...定时器] 定时器 回调4`),0)

process.nextTick( () => {
    console.log(`[...待切入下一个阶段] nextTick 回调1`)
})
process.nextTick( () => {
    console.log(`[...待切入下一个阶段] nextTick 回调2`)
    process.nextTick( () => {
        console.log(`[...待切入下一个阶段] nextTick 回调4`)
    })
})

process.nextTick( () => {
    console.log(`[...待切入下一个阶段] nextTick 回调3`)
})
